package com.wswy.wzcx.ui.main.mine

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.os.SystemClock
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.DataCenter
import com.wswy.wzcx.model.UserMode
import com.wswy.wzcx.model.convert
import com.wswy.wzcx.model.core.EventTabConfResp
import com.wswy.wzcx.model.home.ExtModule
import com.wswy.wzcx.module.LocManager
import com.wswy.wzcx.module.base.UserViewModel
import com.wswy.wzcx.module.base.onResult
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit

class MineViewModel : UserViewModel() {

    private val cityLiveData = MutableLiveData<String?>()

    private val mineItemLiveData = MutableLiveData<List<ExtModule>?>()

    private var lastReloadInfo = 0L

    override fun onCreate() {
        super.onCreate()
        registerObservers()
        getLocation()
        reloadUserInfo()
    }

    override fun autoRegisterEvent(): Boolean {
        return true
    }

    override fun onUserLoginSuccess(userMode: UserMode?) {
        super.onUserLoginSuccess(userMode)
        getLocation()

    }

    private fun getLocation(){

        LocManager.getInstance().currentLocation?.city.let {
            cityLiveData.postValue(it)
        }
    }

    fun reloadUserInfo(){
        if (hasLogin()) {
            if (lastReloadInfo != 0L && SystemClock.elapsedRealtime() - lastReloadInfo < TimeUnit.MINUTES.toMillis(5)){
                return
            }

            lastReloadInfo= SystemClock.elapsedRealtime()

            addRun(Api.get().userInfo.onResult({

                it?.run {
                    super.onUserLoginSuccess(this)
                    DataCenter.get().saveUserModeWithoutNotify(this)
                }

            }, {

            }))
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onEventTabConfResp(resp: EventTabConfResp) {
        resp.tabConfResp?.mine?.convert()?.run {
            flatMapTo(arrayListOf()){
                it.value
            }.run {
                mineItemLiveData.postValue(this)
            }
        }
    }


    fun getCityLiveData():LiveData<String?> = cityLiveData

    fun getMineModels():LiveData<List<ExtModule>?> = mineItemLiveData

}